import { type AxiosPromise } from "axios";
import { get, post } from "@/utils/request";
import { useMutation, useQueryClient } from "@tanstack/react-query";

export const dictKeys = {
  all: () => ["dicts"],
  dictsTableTree: () => ["dictsTableTree"],
  dictsSelectTree: () => ["dictsSelectTree"],
  detail: (name: string) => [...dictKeys.all(), name],
};

export interface DictQueryParams {
  [key: string]: unknown;
}

export const dicts = (data: DictQueryParams = {}): AxiosPromise => {
  return get("/dicts", data);
};

// For consistency with roles API, but returns a flat list.
export const dictsTableTree = (data: DictQueryParams = {}): AxiosPromise => {
  return get("/dicts", data);
};

// For consistency with roles API, but returns a flat list.
export const dictsSelectTree = (data: DictQueryParams = {}): AxiosPromise => {
  return get("/dicts", data);
};

export const dictGet = (name: string): AxiosPromise => {
  return get(`/dicts/get/${name}`);
};

export interface DictAddData {
  name: string;
  value: Array<{ name: string; value: string }>;
}

export const dictAdd = (data: DictAddData): AxiosPromise => {
  return post("/dicts", data);
};

export interface DictDeleteData {
  name: string[];
}

export const dictDelete = (data: DictDeleteData): AxiosPromise => {
  return post("/dicts/delete", data);
};

export interface DictUpdateData {
  id: number;
  name?: string;
  value?: Array<{ name: string; value: string }>;
}

export const dictUpdate = (data: DictUpdateData): AxiosPromise => {
  return post("/dicts/update", data);
};

export function useDictAdd() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (newData: DictAddData) => {
      await queryClient.cancelQueries({ queryKey: dictKeys.all() });
      return dictAdd(newData);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: dictKeys.all() });
      queryClient.invalidateQueries({ queryKey: dictKeys.dictsTableTree() });
    },
  });
}

export function useDictDelete() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: DictDeleteData) => {
      return dictDelete(data);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: dictKeys.all() });
      queryClient.invalidateQueries({ queryKey: dictKeys.dictsTableTree() });
    },
  });
}

export function useDictUpdate() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (data: DictUpdateData) => {
      return dictUpdate(data);
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: dictKeys.all() });
      queryClient.invalidateQueries({ queryKey: dictKeys.dictsTableTree() });
      // 如果更新了字典名称，可能需要更新详情缓存
      if (variables.name) {
        queryClient.invalidateQueries({
          queryKey: dictKeys.detail(variables.name),
        });
      }
    },
  });
}
